<!--
 * 用户缴费信息
 *
-->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item>
              <i class="iconfont icon-stall-fee-menu" style="margin: 5px; font-size: 22px">
                    缴费信息
              </i ></el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col :span="24">
                    <div class="left">
                        <div class="top">
                            <el-row>
                                <el-col :span="24" style="text-align: left">
                                    <i class="iconfont icon-stall-fee-menu"
                                        style="font-size: 32px"
                                    > 账户余额
                                    </i>
                                </el-col>
                            </el-row>
                            <div class="count" v-if="userInfo.money">
                                <span class="num">￥</span>
                                <span class="num">{{
                                    userInfo.money.toFixed(2)
                                }}</span>
                            </div>
                            <br />
                            <el-button
                                class="pay-btn"
                                style="font-size: 22px"
                                type="primary"
                                @click="toPay"
                            ><i
                                class="iconfont icon-add-button"
                                style="font-size: 22px"
                            ></i>
                                立即充值</el-button
                            >
                        </div>
                    </div>
                </el-col>
                <hr />
                <el-col :span="24">
                    <div class="bottom">
                        <el-row>
                            <el-col :span="24" style="text-align: left">
                                <i class="iconfont icon-wait-fee"
                                    style="font-size: 32px; font-weight: 600"
                                > 待缴费</i>
                            </el-col>
                        </el-row>

                        <el-row style="font-weight: 600; font-size: 22px;margin-top: 10px;">
                            <el-col :span="6"> 区域 </el-col>
                            <el-col :span="4"> 车位号 </el-col>
                            <el-col :span="8"> 时间 </el-col>
                            <el-col :span="6"> 操作 </el-col>
                        </el-row>
                        <div v-for="(item, index) in dRes" :key="index">
                            <el-row v-if="item" style="height: 30px; border-bottom: 1px #909399 dotted">
                                <el-col :span="6">{{ item.stall.stallArea }}</el-col>
                                <el-col :span="4">{{ item.stall.stallNum }}</el-col>
                                <el-col :span="8">{{ dateFormat(item.createTime, 3) }}</el-col>
                                <el-col :span="6">
                                    <template v-if="item.calculatedFee !== undefined">
                                        {{ item.calculatedFee.toFixed(2) }}元
                                        <el-button
                                            type="primary"
                                            size="mini"
                                            icon="el-icon-money"
                                            circle
                                            @click="payStall(item)"
                                        ></el-button>
                                    </template>
                                    <template v-else>
                                        <el-tag size="mini" type="info">计算中...</el-tag>
                                    </template>
                                </el-col>
                            </el-row>
                        </div>
                        <div v-if="dRes.length == 0" class="no-res">
                            没有相关记录
                        </div>
                    </div>
                </el-col>
                <hr />
                <el-col :span="24">
                    <div class="right">
                        <el-row>
                            <el-col :span="24" style="text-align: left">
                                <i
                                    class="iconfont icon-wait-fee"
                                    style="font-size: 32px; font-weight: 600"
                                >
                                    缴费记录</i
                                >
                            </el-col>
                        </el-row>
                        <el-row style="font-weight: 600; font-size: 22px;margin-top: 10px;">
                            <el-col :span="6"> 区域 </el-col>
                            <el-col :span="4"> 车位号 </el-col>
                            <el-col :span="8"> 时间 </el-col>
                            <el-col :span="6"> 费用 </el-col>
                        </el-row>
                        <el-row v-for="item in allStallRes" :key="item.id">
                            <el-col :span="6">
                                <span class="area">{{
                                    item.stall.stallArea
                                }}</span>
                            </el-col>
                            <el-col :span="4">
                                <samp class="stall-num">{{
                                    item.stall.stallNum
                                }}</samp>
                            </el-col>
                            <el-col :span="8">
                                <span class="create-time">{{
                                    item.createTime
                                }}</span>
                            </el-col>
                            <el-col :span="6">
                                <span
                                    class="money"
                                    v-if="
                                        item.money != undefined &&
                                        item.money != null
                                    "
                                    >缴费：{{ item.money.toFixed(2) }}元</span
                                >
                                <span class="money num-red" v-else
                                    >待缴费：{{
                                        feeChange(item).toFixed(2)
                                    }}元</span
                                >
                            </el-col>
                        </el-row>
                        <div v-if="allStallRes.length == 0" class="no-res">
                            没有相关记录
                        </div>
                    </div>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog
            title="充值"
            :visible.sync="payShow"
            width="500px"
            center
            @close="payClose"
        >
            <!-- 内容主题区域 -->
            <el-input
                v-model.number="payMoney"
                @blur="checkMoney"
                placeholder="充值金额"
                style="width: 300px"
            ></el-input>
            <br />
            <span class="pay-msg" v-if="msgShow">{{ payMsg }}</span>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <!-- <el-button @click="payClose">取 消</el-button> -->
                <el-button type="primary" @click="payClick">确认充值</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import axios from "axios";
export default {
    data() {
        return {
            allStallRes: [],
            userInfo: {},
            payShow: false,
            payMoney: "",
            payMsg: "",
            msgShow: false,
            dRes: [],
        };
    },
    methods: {
        getAllStallRes(uid) {
            axios.get("/stall/listUserStallRes?person=" + uid).then((res) => {
                this.allStallRes = res.data.data;
            });
        },
        getUserInfo(uid) {
            axios.get("/user/getUserByUid?uid=" + uid).then((res) => {
                this.userInfo = res.data.data;
                if (this.userInfo.username) {
                    this.getAllStallRes(this.userInfo.username);
                    this.getUserNoPay(this.userInfo.username);
                }
            });
        },
        getUserNoPay(uid) {
            axios.get("/stall/allNoPay?person=" + uid).then((res) => {
                this.dRes = res.data.data;
                
                // 为每个未结算的停车记录计算费用
                this.dRes.forEach(item => {
                    this.calculateFee(item);
                });
            });
        },
        getUserStallRes(uid) {
            axios.get("/stall/allRes?uid=" + uid).then((res) => {
                this.yRes = res.data.data;
            });
        },
        feeChange(stallRes) {
            let startTime = new Date(stallRes.createTime);
            let endTime = new Date();
            let hours = (endTime.getTime() - startTime.getTime()) / 3600000;
            
            // 获取车辆类型
            let carType = stallRes.carType || "小型车"; // 默认为小型车
            
            // 调用获取费率的方法
            return this.getRate(carType, hours);
        },
        // 获取当前车辆类型和时间段的费率
        getRate(carType, hours) {
            // 模拟从服务器获取费率配置
            // 实际项目中应该通过API调用获取
            return new Promise((resolve, reject) => {
                axios.get("/fee-setting/list", {
                    params: {
                        carType: carType
                    }
                }).then(res => {
                    if (res.data && res.data.data && res.data.data.length > 0) {
                        const feeRates = res.data.data;
                        
                        // 获取当前时间
                        const now = new Date();
                        const currentHour = now.getHours();
                        const currentMinutes = now.getMinutes();
                        const currentTimeString = `${String(currentHour).padStart(2, '0')}:${String(currentMinutes).padStart(2, '0')}`;
                        
                        // 查找适用于当前时间的费率
                        let applicableRate = null;
                        
                        for (const rate of feeRates) {
                            // 检查时间段是否适用
                            if (this.isTimeInRange(currentTimeString, rate.startTime, rate.endTime)) {
                                applicableRate = rate;
                                break;
                            }
                        }
                        
                        // 如果没有找到适用的费率，使用默认费率
                        if (!applicableRate && feeRates.length > 0) {
                            applicableRate = feeRates[0];
                        }
                        
                        // 计算费用
                        const fee = applicableRate ? (Math.floor(hours * 10) / 10) * applicableRate.money : 0;
                        resolve(fee);
                    } else {
                        // 使用默认费率
                        const defaultRate = 5; // 默认每小时5元
                        const fee = (Math.floor(hours * 10) / 10) * defaultRate;
                        resolve(fee);
                    }
                }).catch(error => {
                    console.error("获取费率失败:", error);
                    // 使用默认费率
                    const defaultRate = 5; // 默认每小时5元
                    const fee = (Math.floor(hours * 10) / 10) * defaultRate;
                    resolve(fee);
                });
            });
        },
        // 判断当前时间是否在时间范围内
        isTimeInRange(current, start, end) {
            // 处理跨天的情况
            if (start > end) {
                return current >= start || current <= end;
            }
            // 正常时间段
            return current >= start && current <= end;
        },
        toPay() {
            this.payMoney = "";
            this.payShow = true;
        },
        checkMoney() {
            if (typeof this.payMoney === "number") {
                this.msgShow = false;
                this.payMsg = "";
            } else {
                this.msgShow = true;
                this.payMsg = "请输入正确的金额数值";
            }
        },
        payClick() {
            if (typeof this.payMoney === "number") {
                const uid = window.sessionStorage.getItem("token");
                axios
                    .post("/user/userPay", {
                        uid: uid,
                        money: this.payMoney,
                    })
                    .then((res) => {
                        if (res.data.data) {
                            this.$message.success("充值成功！");
                            this.getUserInfo(uid);
                            this.payClose();
                        } else {
                            this.$message.error("充值失败，请重新尝试");
                        }
                    });
            } else {
                this.$message.info("输入金额错误，充值失败！");
                this.payClose();
            }
        },
        payClose() {
            this.payShow = false;
            this.msgShow = false;
            this.payMsg = "";
        },
        async payStall(stallRes) {
            // 确保费用已计算
            if (stallRes.calculatedFee === undefined) {
                await this.calculateFee(stallRes);
                // 等待费用计算完成
                await new Promise(resolve => setTimeout(resolve, 500));
            }
            
            const re = await this.$confirm(
                "该次停车缴费" + stallRes.calculatedFee.toFixed(2) + "元?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch((err) => err);
            
            if (re != "confirm") {
                this.$message.info("已取消停车缴费！");
            } else {
                let oa = {};
                oa.pid = stallRes.pid;
                oa.person = stallRes.person;
                oa.stallId = stallRes.stallId;
                oa.money = stallRes.calculatedFee;
                axios.post("/stall/payMoneyPerson", oa).then((res) => {
                    if (res.data.data.flag) {
                        this.$message.success("停车缴费成功！");
                        this.getAllStallRes(this.userInfo.username);
                        this.getUserNoPay(this.userInfo.username);
                    } else {
                        this.$message.error(res.data.data.msg);
                    }
                });
            }
        },
        // 计算费用并保存到记录中
        calculateFee(stallRes) {
            let startTime = new Date(stallRes.createTime);
            let endTime = new Date();
            let hours = (endTime.getTime() - startTime.getTime()) / 3600000;
            
            // 获取车辆类型
            let carType = stallRes.carType || "小型车"; // 默认为小型车
            
            // 调用获取费率的方法
            this.getRate(carType, hours).then(fee => {
                // 使用Vue.set确保响应性
                this.$set(stallRes, 'calculatedFee', fee);
            });
        },
    },

    mounted() {
        const uid = window.sessionStorage.getItem("token");
        this.getUserInfo(uid);
    },
};
</script>
<style scoped>
.top {
    height: 200px;
}
.top h2 {
    text-align: center;
    color: rgb(102, 102, 102);
}
.count {
    text-align: left;
    color: #e75c09;
}
.num {
    font-size: 34px;
}
.text {
    font-size: 20px;
}
.pay-btn {
    margin-left: 8%;
    width: 180px;
    transform: translateX(-90px);
}
.bottom {
}
.bottom h2 {
    text-align: center;
    color: rgb(102, 102, 102);
}
.right {
}
.el-row {
    height: 50px;
}
.right h2 {
    text-align: center;
    font-size: 24px;
    color: rgb(107, 107, 107);
}
.pay-msg {
    color: red;
    font-size: 12px;
}
.stall-num {
    font-size: 16px;
}
.num-red {
    color: red;
}
.no-res {
    width: 100%;
    height: 150px;
    line-height: 150px;
    text-align: center;
    color: rgb(203, 199, 199);
    font-size: 24px;
}
</style>
